package cc.rengu.igas.channel.nucc.core.realize.impl;

import cc.rengu.igas.channel.nucc.common.constant.NuccParamConstant;
import cc.rengu.igas.channel.nucc.core.realize.NuccSeqNoManage;
import cc.rengu.oltp.service.common.dao.SequenceMapper;
import cc.rengu.oltp.service.common.dao.impl.SequenceMapperImpl;
import cc.rengu.oltp.utility.util.RedisUtil;
import cc.rengu.utility.base.TimeUtil;
import cc.rengu.utility.cache.UnifiedCache;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;

import java.util.Random;

public class NuccSeqNoManageImpl implements NuccSeqNoManage {
    RgLogger rglog = RgLog.getLogger(this.getClass().getName());

    @Override
    public String genEpccSeqNo() throws Exception {
        /**
         * 流水号生成规则 31 位交易流水号组成
         * 规则为：“ 8 位日期” +“ 1 6 位序列号（MMddHHmmss+6位序列号）” +“ 1 位预留位” +“ 6 位控制位”
         */
        /*获取从缓存流水号控制位*/
        String epccCtrlNb = RedisUtil.onceGet(NuccParamConstant.EPCC_CTRL_NB_CAC);
        if (null == epccCtrlNb || epccCtrlNb.isEmpty()) {
            rglog.error("从Redis中获取idc列表失败");
            return null;
        }
        rglog.info("网联流水号列表[{}]", epccCtrlNb);
        String[] ctrlNbList = epccCtrlNb.split("\\|");
        //随机获取一个流水号
        Random random = new Random();
        String ctrlNb = ctrlNbList[random.nextInt(ctrlNbList.length)];
        rglog.info("ctrlNb[{}]", ctrlNb);

        //预留位
        String reserve = (String) UnifiedCache.get("epcc", "testFlag");

        //获取顺序号
        SequenceMapper sequenceMapper = new SequenceMapperImpl();
        String transSeqNo = sequenceMapper.getNextTransSequenceNo(6);
        if (null == transSeqNo) {
            rglog.error("生成交易流水序列号失败!");
            return null;
        }
        String dateTime = TimeUtil.getDateTime("yyyyMMddHHmmss");

        return dateTime.substring(0, 8) + dateTime.substring(4) + transSeqNo + reserve + ctrlNb;
    }
}
